package com.nova.android.tvlauncher.ui.adapter.atv

import android.widget.ImageView
import androidx.core.view.isVisible
import com.nova.android.tvlauncher.AppCache
import com.nova.android.tvlauncher.databinding.ItemSelectAppAtvBinding
import com.nova.android.tvlauncher.constants.ConstantsAtv
import com.shudong.lib_base.ext.appContext
import com_github_lib_base.bean.FavoriteApp
import com_github_lib_base.currentActivity
import com_github_lib_base.ext.clickNoRepeat
import com_github_lib_base.ext.createDrawable
import com_github_lib_base.ext.isBanner
import com_github_lib_base.ext.rv.BindAdapter
import sendLiveEventData

object HomeSelectAppAtvAdapter {
    fun bindData(
        binding: BindAdapter,
    ) {

        binding.apply {
            val itemBinding = getBinding<ItemSelectAppAtvBinding>()
            val item = getModel<FavoriteApp>()

            itemBinding.tvAppName.text = item.displayName
            showIcon(item, itemBinding)
            itemClick(item, itemBinding)
        }
    }

    private fun showIcon(item: FavoriteApp, itemBinding: ItemSelectAppAtvBinding) {
        val drawable = item.createDrawable(appContext)
        if (drawable.isBanner()) {
            // 横屏 Banner 的处理逻辑
            itemBinding.ivBigicon.scaleType = ImageView.ScaleType.FIT_CENTER
            itemBinding.ivBigicon.setImageDrawable(drawable)
            itemBinding.ivIcon.isVisible = false
            itemBinding.ivBigicon.isVisible = true
        } else {
            // Icon 的处理逻辑
            itemBinding.ivIcon.setImageDrawable(drawable)
            itemBinding.ivIcon.isVisible = true
            itemBinding.ivBigicon.isVisible = false
        }

    }

    private fun itemClick(item: FavoriteApp, itemBinding: ItemSelectAppAtvBinding) {

        itemBinding.root.clickNoRepeat {
            val favouriteApps = AppCache.favoriteAppList
            favouriteApps.add(item)
            AppCache.favoriteAppList = favouriteApps
            sendLiveEventData(ConstantsAtv.REFRESH_FAVORITE_APPS, item)
            currentActivity?.let { it.finish() }
        }

    }
}